const Client = require('ssh2-sftp-client')
const path = require('path')

class UploadSshPlugin {
  constructor(options) {
    this.config = options
    this.client = new Client('upload-test')
    this.Ver = options.Ver
    this.baseUrl = '/home/cdn/ds/'
    this.dst = '/home/cdn/ds/' + this.Ver
    this.src = path.resolve(__dirname, '../dist')
  }

  apply(compiler) {
    compiler.hooks.done.tap('UploadSshPlugin', stats => {
      this.upload().then(msg => {
        console.log(msg, '上传完成')
      })
        .catch(err => {
          console.log(`main error: ${err.message}`, this.index)
        })
    })
  }

  async upload() {
    try {
      await this.client.connect(this.config)
      const exists = await this.client.exists(this.dst)
      const data = await this.client.list(this.baseUrl)
      console.log(data)
      // 删除服务器文件 比较不安全 需要再看看
      // if (Array.isArray(data) && data.length > 2) {
      //   const filter = data.filter(item => {
      //     return (this.Ver / 1000 - item.accessTime / 1000) > 604800
      //   })
      //   for (const item of filter) {
      //     await this.client.rmdir('/home/cdn/ds/' + item.name, true)
      //   }
      // }
      if (!exists) {
        this.client.on('upload', info => {
          console.log(`Listener: Uploaded ${info.source}`)
        })
        const rslt = await this.client.uploadDir(this.src, this.dst)
        return rslt
      } else {
        throw new Error('版本已经存在')
      }
    } finally {
      this.client.end()
    }
  }
}

module.exports = UploadSshPlugin
